//
//  PrivacySetVC.swift
//  YueChat
//
//  Created by IMac on 2024/9/13.
//

import UIKit
import RxSwift
import RxCocoa
import RxRelay

class PrivacySetVC: BaseVC {
    var addFriendArray : Array<Any> = []
    var addIndex : Int = 0
   
    override func viewDidLoad() {
        super.viewDidLoad()

        title = "隐私设置"
        setup()
        self.getUserInfo()
    }


    func setup () {
        
        tableView.register(UINib(nibName: "SubTitleCell", bundle: nil), forCellReuseIdentifier: "SubTitleCell")
        tableView.register(UINib(nibName: "SwitchCell", bundle: nil), forCellReuseIdentifier: "SwitchCell")
        
        dataSource = ["加我为好友的方式","黑名单管理"]
        addFriendArray = [KLocalizedString("AllowAllAdd"),KLocalizedString("AllowAddVerify"),KLocalizedString("AllowAddNo")]
        self.tableView.reloadData()
        
        
    }
    

    func getUserInfo () {
        Task {
            let user = await gosnUser.fetchUserInfo(gosnUser.myId())
                
            await MainActor.run {
                
                if !user!.role.isEmpty {
                    if let roles = try? JSONSerialization.jsonObject(with: Data(user!.role.utf8), options: []) as? [String: Any] {
                        if let addFriendValue = roles["AddFriend"] as? String {
                            self.addIndex = Int(addFriendValue)!
                            self.tableView.reloadData()
                        }
                    }
                }
            
                    
            }
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 60
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 1 {
            return 1
        }
        return dataSource.count
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
//        if section == 1 {
//            return 1.000
//        }
       return 0.001
    }

    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 10
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.section == 1 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchCell", for: indexPath) as! SwitchCell
            cell.titleLab.text = "允许临时聊天"
            cell.type = .AllowTemporaryType
            if let user = gosnUser.getUserInfo(""){
                cell.sw.setOn((user.isAllowTemporaryChat()), animated: true)
                // 监听UISwitch的状态变化
//                cell.sw.rx.value
//                    .subscribe(onNext: { [weak self] (value) in
//                    })
//                    .disposed(by: disposeBag)
            }
           
            return cell
        }
        let str = dataSource[indexPath.row] as? String
        let cell = tableView.dequeueReusableCell(withIdentifier: "SubTitleCell", for: indexPath) as! SubTitleCell
        if indexPath.row == 0 {
            cell.subTitleLab.text = (self.addFriendArray[addIndex] as! String)
        }
        cell.titleLab.text = str
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        tableView.deselectRow(at: indexPath, animated: true)
        
        if indexPath.row == 0 {
//            self.presentVC(VC: ForgotVC())
            self.changeAddFriend()
        }else if indexPath.row == 1 {
            self.navigationController?.pushViewController(BlackListVC(), animated: true)
        }
    }
    
    func changeAddFriend() {
        let alertController = UIAlertController(title: KLocalizedString("AddFriend"), message: "", preferredStyle: .actionSheet)

        let cancelAction = UIAlertAction(title: KLocalizedString("Cancel"), style: .cancel) { _ in
            // 取消操作
        }

        let allowAllAdd = UIAlertAction(title: KLocalizedString("AllowAllAdd"), style: .default) { _ in
            self.addIndex = 0
            self.roleType()
            self.tableView.reloadData()
        }

        let allowAddVerify = UIAlertAction(title: KLocalizedString("AllowAddVerify"), style: .default) { _ in
            self.addIndex = 1
            self.roleType()
            self.tableView.reloadData()
        }

        let allowAddNo = UIAlertAction(title: KLocalizedString("AllowAddNo"), style: .default) { _ in
            self.addIndex = 2
            self.roleType()
            self.tableView.reloadData()
        }

        alertController.addAction(allowAllAdd)
        alertController.addAction(allowAddVerify)
        alertController.addAction(allowAddNo)
        alertController.addAction(cancelAction)

        if let popoverController = alertController.popoverPresentationController {
            popoverController.permittedArrowDirections = []
            popoverController.sourceView = self.view
            popoverController.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
        }

        present(alertController, animated: true, completion: nil)
    }
    
    func roleType() {
        MHAlert.showLoading()
        Task {
            let res = await gosnUser.setUserAddFriendType("\(self.addIndex)")
            await MainActor.run {
                if res {
                    MHAlert.showMessage(KLocalizedString("AlertSettingSuccess"))
                }else{
                    MHAlert.showMessage(KLocalizedString("GroupMessageTimeOut"))
                }
            }
        }
    }

}
